<template>
  <div class="payment-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="container">
        <h1>缴费确认</h1>
        <p class="subtitle">校测费用在线缴纳</p>
      </div>
    </div>

    <!-- 主要内容 -->
    <div class="container">
      <!-- 面包屑导航 -->
      <Breadcrumb />
      
      <div class="main-content">
        <!-- 查询入围信息 -->
        <el-card class="query-card" shadow="hover">
          <template #header>
            <h2><el-icon><Search /></el-icon> 身份验证</h2>
          </template>
          
          <el-form 
            ref="verifyFormRef"
            :model="verifyForm" 
            :rules="verifyRules" 
            label-width="120px"
            size="large"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="身份证号" prop="idCard">
                  <el-input 
                    v-model="verifyForm.idCard" 
                    placeholder="请输入身份证号"
                    maxlength="18"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="姓名" prop="studentName">
                  <el-input 
                    v-model="verifyForm.studentName" 
                    placeholder="请输入姓名"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item>
              <el-button 
                type="primary" 
                size="large" 
                :loading="verifying"
                @click="verifyQualification"
              >
                {{ verifying ? '验证中...' : '验证入围资格' }}
              </el-button>
              <el-button size="large" @click="resetVerifyForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 缴费信息 -->
        <el-card v-if="qualificationInfo && qualificationInfo.qualificationStatus === 'qualified'" class="payment-info-card" shadow="hover">
          <template #header>
            <h2><el-icon><Money /></el-icon> 缴费信息</h2>
          </template>

          <div class="payment-content">
            <!-- 学生信息 -->
            <div class="student-info">
              <h3>考生信息</h3>
              <div class="info-grid">
                <div class="info-item">
                  <span class="label">姓名：</span>
                  <span class="value">{{ qualificationInfo.studentName }}</span>
                </div>
                <div class="info-item">
                  <span class="label">身份证号：</span>
                  <span class="value">{{ maskIdCard(qualificationInfo.idCard) }}</span>
                </div>
                <div class="info-item">
                  <span class="label">报考院校：</span>
                  <span class="value">{{ qualificationInfo.schoolName }}</span>
                </div>
                <div class="info-item">
                  <span class="label">报考专业：</span>
                  <span class="value">{{ qualificationInfo.majorName }}</span>
                </div>
              </div>
            </div>

            <!-- 缴费详情 -->
            <div class="fee-details">
              <h3>费用详情</h3>
              <div class="fee-list">
                <div class="fee-item">
                  <div class="fee-info">
                    <span class="fee-name">校测考试费</span>
                    <span class="fee-desc">提前招生校测考试费用</span>
                  </div>
                  <div class="fee-amount">¥{{ paymentInfo.examFee }}</div>
                </div>
                <div v-if="paymentInfo.materialFee > 0" class="fee-item">
                  <div class="fee-info">
                    <span class="fee-name">材料审核费</span>
                    <span class="fee-desc">报名材料审核费用</span>
                  </div>
                  <div class="fee-amount">¥{{ paymentInfo.materialFee }}</div>
                </div>
                <div class="fee-total">
                  <span class="total-label">应缴总额：</span>
                  <span class="total-amount">¥{{ paymentInfo.totalAmount }}</span>
                </div>
              </div>
            </div>

            <!-- 缴费状态 -->
            <div class="payment-status">
              <h3>缴费状态</h3>
              <div class="status-content">
                <el-tag 
                  :type="getPaymentStatusType(paymentInfo.paymentStatus)"
                  size="large"
                  class="status-tag"
                >
                  {{ getPaymentStatusText(paymentInfo.paymentStatus) }}
                </el-tag>
                <p v-if="paymentInfo.paymentStatus === 'pending'" class="status-desc warning">
                  请在{{ paymentInfo.paymentDeadline }}前完成缴费
                </p>
                <p v-else-if="paymentInfo.paymentStatus === 'paid'" class="status-desc success">
                  缴费已完成，缴费时间：{{ paymentInfo.paymentTime }}
                </p>
                <p v-else-if="paymentInfo.paymentStatus === 'overdue'" class="status-desc danger">
                  缴费已超期，请联系招生办公室
                </p>
              </div>
            </div>

            <!-- 支付方式 -->
            <div v-if="paymentInfo.paymentStatus === 'pending'" class="payment-methods">
              <h3>支付方式</h3>
              <el-radio-group v-model="selectedPaymentMethod" size="large">
                <el-radio value="alipay" class="payment-method">
                  <div class="method-content">
                    <el-icon class="method-icon" color="#1677FF"><CreditCard /></el-icon>
                    <span class="method-name">支付宝</span>
                  </div>
                </el-radio>
                <el-radio value="wechat" class="payment-method">
                  <div class="method-content">
                    <el-icon class="method-icon" color="#07C160"><CreditCard /></el-icon>
                    <span class="method-name">微信支付</span>
                  </div>
                </el-radio>
                <el-radio value="bank" class="payment-method">
                  <div class="method-content">
                    <el-icon class="method-icon" color="#FF6900"><CreditCard /></el-icon>
                    <span class="method-name">银行卡</span>
                  </div>
                </el-radio>
              </el-radio-group>

              <div class="payment-actions">
                <el-button 
                  type="primary" 
                  size="large" 
                  :disabled="!selectedPaymentMethod"
                  :loading="processing"
                  @click="proceedPayment"
                >
                  {{ processing ? '处理中...' : `立即支付 ¥${paymentInfo.totalAmount}` }}
                </el-button>
              </div>
            </div>

            <!-- 已缴费信息 -->
            <div v-else-if="paymentInfo.paymentStatus === 'paid'" class="payment-complete">
              <div class="complete-info">
                <el-icon class="success-icon" size="60" color="#67c23a"><CircleCheckFilled /></el-icon>
                <h3>缴费成功</h3>
                <p>您已成功完成校测费用缴纳</p>
                <div class="payment-details">
                  <div class="detail-item">
                    <span>交易单号：</span>
                    <span>{{ paymentInfo.transactionId }}</span>
                  </div>
                  <div class="detail-item">
                    <span>缴费时间：</span>
                    <span>{{ paymentInfo.paymentTime }}</span>
                  </div>
                  <div class="detail-item">
                    <span>缴费金额：</span>
                    <span>¥{{ paymentInfo.totalAmount }}</span>
                  </div>
                </div>
                <div class="next-steps">
                  <el-button type="primary" @click="goToExam">查看考纲</el-button>
                  <el-button @click="downloadReceipt">下载缴费凭证</el-button>
                </div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 无入围资格提示 -->
        <el-card v-else-if="qualificationInfo && qualificationInfo.qualificationStatus !== 'qualified'" class="no-qualification-card" shadow="hover">
          <div class="no-qualification">
            <el-icon class="warning-icon" size="60" color="#e6a23c"><Warning /></el-icon>
            <h3>暂无缴费权限</h3>
            <p>您暂未获得入围资格或入围资格审核中</p>
            <el-button type="primary" @click="goToQualified">查看入围信息</el-button>
          </div>
        </el-card>

        <!-- 缴费须知 -->
        <el-card class="notice-card" shadow="hover">
          <template #header>
            <h2><el-icon><InfoFilled /></el-icon> 缴费须知</h2>
          </template>
          <div class="notice-content">
            <ol>
              <li>仅获得入围资格的考生需要缴费，请按时完成缴费</li>
              <li>缴费截止时间为入围名单公布后3个工作日</li>
              <li>逾期未缴费视为自动放弃校测资格</li>
              <li>缴费成功后请妥善保存缴费凭证</li>
              <li>如遇缴费问题请及时联系院校招生办公室</li>
              <li>退费规则请参考各院校招生章程</li>
            </ol>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 支付对话框 -->
    <el-dialog v-model="paymentDialogVisible" title="支付确认" width="400px" center>
      <div class="payment-dialog">
        <div class="payment-summary">
          <h4>支付信息确认</h4>
          <div class="summary-item">
            <span>支付方式：</span>
            <span>{{ getPaymentMethodName(selectedPaymentMethod) }}</span>
          </div>
          <div class="summary-item">
            <span>应付金额：</span>
            <span class="amount">¥{{ paymentInfo.totalAmount }}</span>
          </div>
        </div>
        <div class="qr-code" v-if="paymentQrCode">
          <img :src="paymentQrCode" alt="支付二维码" />
          <p>请使用{{ getPaymentMethodName(selectedPaymentMethod) }}扫码支付</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="paymentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPayment">确认支付</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Money, 
  CreditCard, 
  CircleCheckFilled, 
  Warning, 
  InfoFilled 
} from '@element-plus/icons-vue'
import Breadcrumb from '@/components/Breadcrumb.vue'
import api from '@/api'

const router = useRouter()

// 响应式数据
const verifyFormRef = ref()
const verifying = ref(false)
const processing = ref(false)
const qualificationInfo = ref(null)
const selectedPaymentMethod = ref('')
const paymentDialogVisible = ref(false)
const paymentQrCode = ref('')

const verifyForm = reactive({
  idCard: '',
  studentName: ''
})

const paymentInfo = reactive({
  examFee: 80,
  materialFee: 0,
  totalAmount: 80,
  paymentStatus: 'pending', // pending, paid, overdue
  paymentDeadline: '2024年4月15日 23:59',
  paymentTime: '',
  transactionId: ''
})

// 表单验证规则
const verifyRules = {
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确', trigger: 'blur' }
  ],
  studentName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ]
}

// 方法
const verifyQualification = async () => {
  try {
    await verifyFormRef.value.validate()
    verifying.value = true
    
    const { data } = await api.get('/enrollment/qualification/query', {
      params: {
        idCard: verifyForm.idCard,
        studentName: verifyForm.studentName
      }
    })
    
    if (data && data.qualificationStatus === 'qualified') {
      qualificationInfo.value = data
      await loadPaymentInfo()
      ElMessage.success('验证成功')
    } else if (data) {
      qualificationInfo.value = data
      ElMessage.warning('您暂未获得入围资格')
    } else {
      ElMessage.warning('未查询到相关信息')
    }
  } catch (error) {
    ElMessage.error('验证失败，请稍后重试')
  } finally {
    verifying.value = false
  }
}

const loadPaymentInfo = async () => {
  try {
    const { data } = await api.get('/enrollment/payment/info', {
      params: {
        idCard: verifyForm.idCard
      }
    })
    Object.assign(paymentInfo, data)
  } catch (error) {
    console.error('加载缴费信息失败:', error)
  }
}

const resetVerifyForm = () => {
  Object.assign(verifyForm, {
    idCard: '',
    studentName: ''
  })
  qualificationInfo.value = null
  verifyFormRef.value?.clearValidate()
}

const maskIdCard = (idCard) => {
  if (!idCard) return ''
  return idCard.replace(/(\d{6})\d{8}(\d{4})/, '$1********$2')
}

const getPaymentStatusType = (status) => {
  const statusMap = {
    pending: 'warning',
    paid: 'success',
    overdue: 'danger'
  }
  return statusMap[status] || 'info'
}

const getPaymentStatusText = (status) => {
  const statusMap = {
    pending: '待缴费',
    paid: '已缴费',
    overdue: '已超期'
  }
  return statusMap[status] || '未知状态'
}

const getPaymentMethodName = (method) => {
  const methodMap = {
    alipay: '支付宝',
    wechat: '微信支付',
    bank: '银行卡'
  }
  return methodMap[method] || ''
}

const proceedPayment = async () => {
  try {
    processing.value = true
    
    // 模拟生成支付二维码
    const { data } = await api.post('/enrollment/payment/create', {
      idCard: verifyForm.idCard,
      paymentMethod: selectedPaymentMethod.value,
      amount: paymentInfo.totalAmount
    })
    
    paymentQrCode.value = data.qrCodeUrl || ''
    paymentDialogVisible.value = true
  } catch (error) {
    ElMessage.error('生成支付信息失败')
  } finally {
    processing.value = false
  }
}

const confirmPayment = async () => {
  try {
    await ElMessageBox.confirm('确认已完成支付？', '支付确认')
    
    // 模拟支付成功
    const { data } = await api.post('/enrollment/payment/confirm', {
      idCard: verifyForm.idCard,
      paymentMethod: selectedPaymentMethod.value
    })
    
    Object.assign(paymentInfo, data)
    paymentDialogVisible.value = false
    ElMessage.success('支付成功！')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('支付确认失败')
    }
  }
}

const goToQualified = () => {
  router.push('/admission/qualified')
}

const goToExam = () => {
  router.push('/admission/exam')
}

const downloadReceipt = () => {
  // 模拟下载缴费凭证
  ElMessage.success('缴费凭证下载成功')
}
</script>

<style lang="scss" scoped>
.payment-page {
  .page-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 60px 0;
    text-align: center;
    
    h1 {
      font-size: 2.5rem;
      margin-bottom: 16px;
      font-weight: 600;
    }
    
    .subtitle {
      font-size: 1.2rem;
      opacity: 0.9;
    }
  }
  
  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
  }
  
  .main-content {
    margin-top: -40px;
    position: relative;
    z-index: 1;
    
    .el-card {
      margin-bottom: 30px;
      border-radius: 12px;
      
      .el-card__header {
        background: #f8f9fa;
        border-bottom: 1px solid #e9ecef;
        
        h2 {
          margin: 0;
          color: #495057;
          display: flex;
          align-items: center;
          gap: 8px;
        }
      }
    }
  }
  
  .payment-content {
    .student-info, .fee-details, .payment-status, .payment-methods {
      margin-bottom: 32px;
      
      h3 {
        margin: 0 0 20px 0;
        padding: 0 0 12px 0;
        border-bottom: 2px solid #409eff;
        color: #303133;
        font-size: 18px;
      }
    }
    
    .info-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
      gap: 16px;
      
      .info-item {
        display: flex;
        align-items: center;
        padding: 12px;
        background: #f8f9fa;
        border-radius: 8px;
        
        .label {
          font-weight: 600;
          color: #606266;
          min-width: 100px;
        }
        
        .value {
          color: #303133;
          font-weight: 500;
        }
      }
    }
    
    .fee-list {
      .fee-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 0;
        border-bottom: 1px solid #eee;
        
        .fee-info {
          .fee-name {
            display: block;
            font-weight: 600;
            color: #303133;
            margin-bottom: 4px;
          }
          
          .fee-desc {
            display: block;
            font-size: 14px;
            color: #909399;
          }
        }
        
        .fee-amount {
          font-size: 18px;
          font-weight: 600;
          color: #f56c6c;
        }
      }
      
      .fee-total {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20px 0;
        font-size: 20px;
        font-weight: 600;
        border-top: 2px solid #409eff;
        margin-top: 16px;
        
        .total-amount {
          color: #f56c6c;
        }
      }
    }
    
    .status-content {
      text-align: center;
      padding: 20px;
      
      .status-tag {
        font-size: 16px;
        padding: 12px 24px;
      }
      
      .status-desc {
        margin-top: 16px;
        font-size: 16px;
        
        &.success {
          color: #67c23a;
        }
        
        &.warning {
          color: #e6a23c;
        }
        
        &.danger {
          color: #f56c6c;
        }
      }
    }
    
    .payment-methods {
      .el-radio-group {
        display: flex;
        gap: 20px;
        margin-bottom: 24px;
        
        .payment-method {
          .method-content {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 16px 20px;
            border: 2px solid #e4e7ed;
            border-radius: 8px;
            transition: all 0.3s;
            
            .method-icon {
              font-size: 24px;
            }
            
            .method-name {
              font-size: 16px;
              font-weight: 500;
            }
          }
          
          &.is-checked .method-content {
            border-color: #409eff;
            background: #f0f9ff;
          }
        }
      }
      
      .payment-actions {
        text-align: center;
      }
    }
    
    .payment-complete {
      .complete-info {
        text-align: center;
        padding: 40px;
        
        .success-icon {
          margin-bottom: 20px;
        }
        
        h3 {
          margin: 0 0 12px 0;
          color: #67c23a;
          font-size: 24px;
        }
        
        > p {
          margin-bottom: 24px;
          color: #606266;
        }
        
        .payment-details {
          background: #f8f9fa;
          padding: 20px;
          border-radius: 8px;
          margin: 24px 0;
          
          .detail-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 12px;
            
            &:last-child {
              margin-bottom: 0;
            }
          }
        }
        
        .next-steps {
          margin-top: 24px;
          
          .el-button {
            margin: 0 8px;
          }
        }
      }
    }
  }
  
  .no-qualification {
    text-align: center;
    padding: 60px 40px;
    
    .warning-icon {
      margin-bottom: 20px;
    }
    
    h3 {
      margin: 0 0 12px 0;
      color: #e6a23c;
      font-size: 24px;
    }
    
    p {
      margin-bottom: 24px;
      color: #606266;
    }
  }
  
  .notice-content {
    ol {
      padding-left: 20px;
      
      li {
        margin-bottom: 12px;
        line-height: 1.6;
        color: #6c757d;
      }
    }
  }
}

.payment-dialog {
  .payment-summary {
    margin-bottom: 20px;
    
    h4 {
      margin: 0 0 16px 0;
      color: #303133;
    }
    
    .summary-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 12px;
      
      .amount {
        font-size: 18px;
        font-weight: 600;
        color: #f56c6c;
      }
    }
  }
  
  .qr-code {
    text-align: center;
    
    img {
      width: 200px;
      height: 200px;
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      margin-bottom: 12px;
    }
    
    p {
      color: #606266;
      font-size: 14px;
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .payment-page {
    .page-header {
      padding: 40px 0;
      
      h1 {
        font-size: 2rem;
      }
      
      .subtitle {
        font-size: 1rem;
      }
    }
    
    .info-grid {
      grid-template-columns: 1fr !important;
    }
    
    .el-radio-group {
      flex-direction: column !important;
    }
    
    .fee-item {
      flex-direction: column;
      align-items: flex-start !important;
      gap: 8px;
    }
  }
}
</style>